package com.nirvana.common.controller;

import com.baomidou.mybatisplus.extension.service.IService;
import com.nirvana.common.dto.BaseResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;
import java.util.List;

/**
 * 通用增删改查、分页等操作接口处理：继承该类即可完成 RESTFul API 基本 CRUD 接口
 * <p>
 * 泛型 T: Model 实体
 * 泛型 S: Service 接口
 *
 * @author zhangshuaiyin
 * @date 2021-08-04 16:43
 */
@Slf4j
public class BizController<T extends Serializable, S extends IService<T>> extends BaseController {

    @Autowired
    protected S baseService;

    @ApiOperation(value = "查询列表", notes = "公共查询列表接口")
    @GetMapping()
    public BaseResponse<List<T>> findList() {
        log.info("common get list...");
        List<T> list = baseService.list();
        return BaseResponse.ok(list);
    }

    @ApiOperation(value = "查询单条记录", notes = "公共根据主键查询单条接口")
    @GetMapping("/{id}")
    public BaseResponse<?> findById(@PathVariable("id") Serializable id) {
        log.info("common get by ID : {}", id);
        T model = baseService.getById(id);
        return BaseResponse.ok(model);
    }

    // TODO 分页查询

    @ApiOperation(value = "新增列表", notes = "公共新增接口")
    @PostMapping()
    public BaseResponse<Boolean> save(@RequestBody T entity) {
        log.info("common save record: {}", entity);
        return BaseResponse.ok(baseService.save(entity));
    }

    @ApiOperation(value = "更新列表", notes = "公共更新接口")
    @PutMapping()
    public BaseResponse<Boolean> update(@RequestBody T entity) {
        log.info("common update record : {}", entity);
        return BaseResponse.ok(baseService.updateById(entity));
    }

    @ApiOperation(value = "删除列表", notes = "公共根据主键删除接口")
    @DeleteMapping("/{id}")
    public BaseResponse<?> remove(@PathVariable("id") Serializable id) {
        log.info("common remove by ID : {}", id);
        return BaseResponse.ok(baseService.removeById(id));
    }
}
